package com.example.controller;



import com.example.domain.Check;
import com.example.domain.Checkid;
import com.example.domain.Resource;
import com.example.service.CheckService;
import com.example.service.CheckidService;
import com.example.service.ResourceService;
import com.example.service.UserService;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class CheckController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private UserService userService;

    @Autowired
    private CheckService checkService;

    @Autowired
    private CheckidService checkidService;

    //展示所有盘点条目
    @ResponseBody
    @RequestMapping("showAllCheck")
    public List<Check> showAllCheck(){
        List<Check> checkList = checkService.showAllCheck();

        int length=checkList.size();
        for (int i=0;i<length;i++){
            Check check = checkList.get(i);
            check.setUname(userService.selectUnameById(check.getInitial_uid()));
            check.setRname(resourceService.selectResourceById(check.getTrue_id()).getRname());
            checkList.set(i,check);
        }
        return checkList;
    }

    //展示当前员工所拥有的的资产的盘点条目
    @ResponseBody
    @RequestMapping("showMyCheck")
    public List<Check> showMyCheck(HttpServletRequest request) throws ParseException {
        HttpSession session = request.getSession();
        Integer uid = Integer.parseInt(session.getAttribute("id").toString());

        //获取当前时间
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String checktime = time.format(new Date());
        Date now=new Date();
        now = format1.parse(checktime);

        List<Check> checkList = checkService.showMyCheck(uid);
        int length=checkList.size();
        for (int i=length-1;i>=0;i--){
            Date completetime = format1.parse(checkList.get(i).getCompletetime());
            int j = completetime.compareTo(now);
            System.out.println(j);
            if (j<0){
                checkList.remove(i);
            }
        }

        length = checkList.size();
        for (int i=0;i<length;i++){
            Check check = checkList.get(i);
            check.setUname(userService.selectUnameById(check.getInitial_uid()));
            check.setRname(resourceService.selectResourceById(check.getTrue_id()).getRname());
            checkList.set(i,check);
        }
        System.out.println(checkList);
        return checkList;
    }

    //普通员工查询资产获取点击盘点那一行的资产id，与扫描到的rid做对比，有相同即为一致
    @ResponseBody
    @RequestMapping(value = "sendMessage",method = RequestMethod.POST)
    public List<Check> SendMessage(@RequestParam("message") String message,
                              @RequestParam("true_id") String rid,
                              @RequestParam("last_time") String lasttime,
                              HttpServletRequest request) {
        List<Check> checkList;
        String result, tips;
        HttpSession session = request.getSession();
        Integer login_uid = Integer.parseInt(session.getAttribute("id").toString());

        System.out.println("messgae"+message+"\nrid:"+rid+"\nlasttime"+lasttime);

        //获取当前时间与最后截止时间
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String checktime = time.format(new Date());
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date last=new Date();
        Date now=new Date();
        try {
            last = format1.parse(lasttime);
            now = format1.parse(checktime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //超时的情况下
        int i = now.compareTo(last);
        if (i>0){
            return null;
        }

        //时间没有超出，进行资产判断
        if (rid.equals(message)) {
            result = "盘点无差异";
            tips = "存在领用编号为" + message + "的资产，盘点无误。";
            System.out.println(tips);
        } else {
            result = "存在差异";
            tips = "不存在编号为：" + rid + "的已领用的资产！扫描到的资产编号是：" + message + "\n盘点结果不一致，请联系管理员！";
            System.out.println(tips);
        }
        //更新结果，当rid与时间相同的时候，更新结果与备注。
        checkService.error(result, tips, rid, lasttime);
        checkList = checkService.showMyCheck(login_uid);
        int length=checkList.size();
        for (int j=0;j<length;j++){
            Check check = checkList.get(j);
            check.setUname(userService.selectUnameById(check.getInitial_uid()));
            check.setRname(resourceService.selectResourceById(check.getTrue_id()).getRname());
            checkList.set(j,check);
        }
        return checkList;
    }

    //管理员查询资产，这里只涉及到了当管理员选择一致的情况（没有用到，现在改成了下面其他的函数的内容了）
    @ResponseBody
    @RequestMapping("managerCheck")
    public String managerCheck(@RequestParam("message") String message){
        //定义盘点单号，后面对比的时候再赋值
        int checkid;
        //获取当前时间
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String checktime = time.format(new Date());
        //获取含有这个资产id的全部盘点单里面的截止时间
        List<String> lasttimelist = checkService.selectCompletetimeById(message);
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date last=new Date();
        Date now=new Date();
        int length = lasttimelist.size();
        //循环每个截止时间与当前时间做对比
        for (int i=0;i<length;i++) {
            try {
                last = format1.parse(lasttimelist.get(i));
                now = format1.parse(checktime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //如果当前时间小于截止时间就表示是这个盘点单
            int j = now.compareTo(last);
            if (j <= 0) {
                checkid=checkidService.selectCheckidByCompletetime(lasttimelist.get(i));
                checkService.updateError("盘点一致",checkid,message);
                return "更新资产编号为"+checkid+"的资产为盘点结果一致";
            }
        }

        return "未找到资产编号为："+message+"的资产\n请确认是否存在该资产或是否存在于盘点期限内的盘点单中。";
    }

    //查询有无含有该资产编号且时间没过期的盘点单
    //12.30:我想把这个函数改了，现在功能好像不全，而且复杂，不如直接判断当前资产里面符合获取扫描到的资产。
    //因为现在的这个函数无法判断出一个角色借了资产但是没有登记的情况，这种情况下用下面的函数会说找不到资产。
//    @ResponseBody
//    @RequestMapping("findCheck")
//    public Check findCheck(@RequestParam("rid") String rid) {
//        //此为修改后版本。注释为修改前版本
//        Integer num = resourceService.hasId(rid);
//        if (num == 0) {
//            return null;
//        }
//        List<String> completelist = checkidService.showAllCompletetime();
//        //获取当前时间
//        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
//        String checktime = time.format(new Date());
//        //修改成Date格式用于对比。
//        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
//        Date last = new Date();
//        Date now = new Date();
//        int length = completelist.size();
//        for (int i = 0; i < length; i++) {
//            try {
//                last = format1.parse(completelist.get(i));
//                now = format1.parse(checktime);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            //如果当前时间小于截止时间就表示是这个盘点单
//            int j = now.compareTo(last);
//            if (j <= 0) {
////                checkid = checkidService.selectCheckidByCompletetime(lasttimelist.get(i)).toString();
////                return checkid;
//            }
//        }
//        return null;
//    }

    @ResponseBody
    @RequestMapping("findCheck")
    public String findCheck(@RequestParam("rid") String rid) {
        //定义盘点单号，后面对比的时候再赋值
        String checkid ;
        //获取当前时间
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String checktime = time.format(new Date());
        //获取含有这个资产id的全部盘点单里面的截止时间
        List<String> lasttimelist = checkService.selectCompletetimeById(rid);
        //test list
        System.out.println(lasttimelist);

        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date last=new Date();
        Date now=new Date();
        int length = lasttimelist.size();
        //循环每个截止时间与当前时间做对比
        for (int i=0;i<length;i++) {
            try {
                last = format1.parse(lasttimelist.get(i));
                now = format1.parse(checktime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //如果当前时间小于截止时间就表示是这个盘点单
            int j = now.compareTo(last);
            if (j <= 0) {
                checkid=checkidService.selectCheckidByCompletetime(lasttimelist.get(i)).toString();
                return checkid;
            }
        }
        //31修改：想了一下30号的那个方案有点麻烦，要不就在这个基础上在前端添加一个判断。
        //如果是error的话再查找一次rid，如果有rid，那么就输出rid这个资产，没有rid那么就说扫的是错的码。
        //1.14补充：31号说的这个好像也不行，如果当前没有任何一个盘点单的话，扫描到的也会说盘点不一致，但是我们根本没有发起盘点。
        //那再做一个判断，上面是循环了所有有这个资产的盘点单，查找其中未过期的盘点单，那么现在
        //遍历全部的盘点单，如果没有未过期盘点单就返回TRUE_ERROR说没有合适的盘点单，如果有的话那就返回ERROR表示这个资产并没有在盘点单里面（也就是借了资产但是并没有登记的情况）
        lasttimelist=checkidService.showAllCompletetime();
        System.out.println(lasttimelist);
        length = lasttimelist.size();
        for (int i=0;i<length;i++){
            System.out.println(i+": "+lasttimelist.get(i));
            try {
                last = format1.parse(lasttimelist.get(i));
                now = format1.parse(checktime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //如果当前时间小于截止时间就表示是这个盘点单
            int j = now.compareTo(last);
            if (j <= 0) {
                return "ERROR";
            }
        }
        return "TRUE_ERROR";
    }

    //通过checkid与rid获取对应的资产
    @ResponseBody
    @RequestMapping("getCheck")
    public Check getCheck(@RequestParam("rid") String rid,
                          @RequestParam("msg") Integer checkid){
        Check check = checkService.selectCheckByCheckidRid(rid,checkid);
        check.setUname(userService.selectUnameById(check.getInitial_uid()));
        check.setRname(resourceService.selectResourceById(check.getTrue_id()).getRname());
        System.out.println(check);
        return check;

    }

    //进行管理员选择的结果判断与修改 的盘点
    @ResponseBody
    @RequestMapping("checkResult")
    public String checkResult(@RequestParam("checkid") Integer checkid,
                              @RequestParam("rid") String rid,
                              @RequestParam("uname") String uname,
                              @RequestParam("right") String result) throws Exception {
        if (result.equals("1")){
            checkService.updateError("盘点一致",checkid,rid);
            return "更新资产编号为"+rid+"的资产为盘点结果一致";
        }else{
            //判断输入的名字是否正确
            String lastname = userService.selectUnameById(resourceService.selectUidById(rid));
            Integer uid = userService.selectIdByUname(uname);
            if (uid == null){
                return null;
            }
            String completetime = checkidService.showCompleteTime(checkid);
            //判断是不是多次盘点,为‘未盘点’表示从来没盘点过，此时可以插入新增数据。有数据表示盘点过，只能修改之前新增的数据。
            if (checkService.selectErrorByCheckidRid(rid,checkid).equals("未盘点")) {
                checkService.refreshCheck(checkid, uid, rid, completetime, "盘点存在差异", "不一致,原用户为：" + lastname + "\n现修改为：" + uname);
                //checkService.error("盘点不一致", "原用户为：" + lastname + "\n现修改为：" + uname, rid, completetime);

                return "不一致,原用户为：" + lastname + "\n现修改为：" + uname;
            }else{
                //先删除原先的差异更新的数据，然后添加一条新的差异更新数据
                checkService.deleteCheckChange2(rid,checkid);
                checkService.refreshCheck(checkid, uid, rid, completetime, "差异更新", "不一致,原用户为：" + lastname + "\n现修改为：" + uname);
                //checkService.error("盘点不一致", "原用户为：" + lastname + "\n现修改为：" + uname, rid, completetime);
                return "多次盘点。\n原用户为：" + lastname + "\n现修改为：" + uname;
            }
        }
    }

    //盘点单里面找不到资产的时候的盘点
    @ResponseBody
    @RequestMapping("noResourceError")
    public String noResourceError(@RequestParam("rid")String rid,
                                  @RequestParam("uname")String uname) throws Exception {
        //判断输入的名字是否正确，正确赋值给uid，不正确就报错。
        String lastname = userService.selectUnameById(resourceService.selectUidById(rid));
        Integer uid = userService.selectIdByUname(uname);
        if (uid == null){
            return null;
        }

        Integer checkid = null;
        //先找到没有过期的盘点单，把这次数据插入到盘点单里面
        //遍历全部的盘点单，上一步已经判断过了有没有未过期的盘点单，所以肯定有未过期盘点单存在
        List<String> lasttimelist=checkidService.showAllCompletetime();
        System.out.println(lasttimelist);
        int length = lasttimelist.size();
        //获取当前时间
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String checktime = time.format(new Date());
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date last=new Date();
        Date now=new Date();
        for (int i=0;i<length;i++){
            System.out.println(i+": "+lasttimelist.get(i));
            try {
                last = format1.parse(lasttimelist.get(i));
                now = format1.parse(checktime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //如果当前时间小于截止时间表示这个盘点单未过期。那就插入这个表里面。
            int j = now.compareTo(last);
            if (j <= 0) {
                checkid = checkidService.selectCheckidByCompletetime(lasttimelist.get(i));
                System.out.println(checkid);
            }
        }
        checkService.insertNoResourceError(checkid,uid,rid,checkidService.showCompleteTime(checkid),"盘点不一致","该资产未录入盘点单，原因：1.发起盘点时未发起该资产盘点。2.资产借出未登记。");
        //上面已经把数据添加到盘点单了，接下来就要修改Resource资产表里面的数据了
//        Resource resource = new Resource();
//        resource.setUid(uid);resource.setRstatus("已借出");resource.setRnum(rid);
//        resource.setBorrowtime(checktime);
//        resourceService.borrowUpdate(resource);
        return "未引入盘点单的资产已修改完成";
    }

    @ResponseBody
    @RequestMapping("showCheckByCheckid")
    public List<Check> showCheckByCheckid(@RequestParam("checkid") Integer checkid){

        List<Check> checkList = checkService.selectCheckByCheckid(checkid);

        int length=checkList.size();
        for (int i=0;i<length;i++){
            Check check = checkList.get(i);
            check.setUname(userService.selectUnameById(check.getInitial_uid()));
            check.setRname(resourceService.selectResourceById(check.getTrue_id()).getRname());
            checkList.set(i,check);
        }
        return checkList;
    }

    //发起盘点，将选择的资产添加到未过期的盘点单号中
    @ResponseBody
    @RequestMapping(value = "startCheck",method = RequestMethod.POST)
    public List<Check> StartCheck(@RequestParam("rid") String rid) throws Exception {
        //此处插入到数据库的方法是先新建一个行，插入rid与uid，插入rid的同时在resource表查找uid，uid不为空才能插入
        //也就是说在mapper文件里面进行了借出判断，只有借出的才能发起盘点。
        //获取当前时间与数据库中的全部时间.
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String nowtime = time.format(new Date());
        List<String> timelist = checkidService.showAllCompletetime();
        int length = timelist.size();

        int checkid=0;//用于记录checkid
        String true_time=null;//用于存储真实的截止时间
        Integer initial_uid = resourceService.selectUidById(rid);

        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date completetime=new Date();
        Date now=new Date();
        try {
            now = format1.parse(nowtime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //循环数据库里面的所有的盘点单号，一条条判断时间是否超过
        for (int j=0;j<length;j++){
            try {
                completetime = format1.parse(timelist.get(j));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //判断：如果当前时间小于盘点限制时间则符合，获取盘点单号赋值给true_time，
            if (now.compareTo(completetime)<0){
                checkid=checkidService.selectCheckidByCompletetime(timelist.get(j));
                true_time=timelist.get(j);
                break;
            }
        }
        //开始判断是否有对应记录，有的话不添加
        List<Check> checklist = checkService.selectCheckByCheckid(checkid);
        int checklength = checklist.size();
        for (int i=0;i<checklength;i++){
            if ((checklist.get(i).getInitial_uid())==initial_uid&&(checklist.get(i).getTrue_id()).equals(rid)){
                System.out.println("一致！");
                return null;
            }
        }

        checkService.startCheck(rid);
        checkService.startTime(true_time,checkid,1);

        List<Check> checkList = checkService.showAllCheck();
        return checkList;
    }

    //导出
    @ResponseBody
    @RequestMapping("export")
    public String export(int[] list) throws Exception{
        Date date  = new Date();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
        SimpleDateFormat time = new SimpleDateFormat("yyyy_MM_dd");
        String exporttime = time.format(new Date());
        //创建一个文件对象
        Workbook book = new HSSFWorkbook();
        //新建一个文件
        File file = new File("D:\\Check\\盘点数据" + exporttime + ".xls");
        FileOutputStream fis ;
        //循环list插入到sheet中
        for (int j=0;j<list.length;j++) {
            //设置一个文件名称
            Sheet sheet = book.createSheet("盘点单号"+list[j]);
            //创建单元格对象
            Row row = sheet.createRow(0);
            row.createCell(0).setCellValue("资产序号");   //第一列
            row.createCell(1).setCellValue("资产名称");  //第二列
            row.createCell(2).setCellValue("工号");//第三列
            row.createCell(3).setCellValue("姓名");//第四列
            row.createCell(4).setCellValue("结束时间");//第五列
            row.createCell(5).setCellValue("盘点状态");//第六列
            row.createCell(6).setCellValue("备注");

            List<Check> checkList = checkService.selectCheckByCheckid(list[j]);
            int length = checkList.size();
            for (int i = 0; i < length; i++) {         //此处是插入名字与资产名字
                Check check = checkList.get(i);
                check.setUname(userService.selectUnameById(check.getInitial_uid()));
                check.setRname(resourceService.selectResourceById(check.getTrue_id()).getRname());
                checkList.set(i, check);
            }
            for (int i = 0; i < length; i++) {        //此处是赋值给表格
                row = sheet.createRow(i + 1);
                Check check = checkList.get(i);
                row.createCell(0).setCellValue(check.getTrue_id());   //第一列
                row.createCell(1).setCellValue(check.getRname());  //第二列
                row.createCell(2).setCellValue(check.getInitial_uid());//第三列
                row.createCell(3).setCellValue(check.getUname());//第四列
                row.createCell(4).setCellValue(check.getCompletetime());//第五列
                row.createCell(5).setCellValue(check.getError());//第六列
                row.createCell(6).setCellValue(check.getTips());
            }
        }
        if (!file.exists()) {   //主要为了方便调试
            fis = new FileOutputStream(file);
            book.write(fis);
            fis.close();
            System.out.println("已经写入>>>>>"+file.toString());
        } else {
            file.delete();
            System.out.println("已经删除>>>>>"+file.toString());
        }
        return file.toString();
    }
}
//        List<String> rid=resourceService.selectRidByUid(login_uid);
//        int length = rid.size();
//        for (int i=0;i<length;i++) {
//            if ((rid.get(i)).equals(message)) {
//                String result = "盘点无差异";
//                String tips = "存在领用编号为" + message + "的资产，盘点无误。";
//                checkService.error(result,tips,message,login_uid);
//                return tips;
//            }
//        }
//        String result = "存在差异";
//        String tips = "不存在编号为：" + message + "的已领用的资产！\n盘点结果不一致，请联系管理员！";
//        checkService.error(result,tips,message,login_uid);
//        return tips;
//    }